//
//  XKRefreshControl.swift
//  XKWeibo
//
//  Created by 小k on 15/11/17.
//  Copyright © 2015年 小k. All rights reserved.
//

import UIKit
import SnapKit
// 下拉刷新的偏移量
private let XKRefreshControlOffset: CGFloat = -60

class XKRefreshControl: UIRefreshControl {
    
    // MARK: - 重写系统方法
    override func endRefreshing() {
        super.endRefreshing()
        
        // 停止动画
        refreshView.stopAnimation()
    }
    
    /// 主动触发开始刷新动画 － 不会触发监听方法
    override func beginRefreshing() {
        super.beginRefreshing()
        
        refreshView.startAnimation()
    }
    
    
    // MARK: - KVO 监听方法
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        if frame.origin.y > 0 {
            return
        }
        
        // 判断是否正在刷新
        if refreshing {
            refreshView.startAnimation()
            return
        }
        
        if frame.origin.y < XKRefreshControlOffset && !refreshView.rotateFlag {
            print("反过来")
            refreshView.rotateFlag = true
        } else if frame.origin.y >= XKRefreshControlOffset && refreshView.rotateFlag {
            print("转过去")
            refreshView.rotateFlag = false
        }
    }

    // MARK: - 重写构造方法
    override init() {
        super.init()
        
        setupUI ()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        
        setupUI ()
    }
    
    private func setupUI () {
        // 1. 添加控件
        addSubview(refreshView)
        
        // 2. 设置布局
        refreshView.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(self.snp_center)
            
            make.size.equalTo(refreshView.bounds.size)
        }
        
        // 3. KVO 监听位置的变化
        dispatch_async(dispatch_get_main_queue()) { () -> Void in
            self.addObserver(self, forKeyPath: "frame", options: [], context: nil)
        }
        
    }
    
    // 删除通知
    deinit {
        self.removeObserver(self, forKeyPath: "frame")
    }
    
    // MARK: - 懒加载控件
    private lazy var refreshView = XKRefreshView.refreshView()

}

// MARK: - 自定义刷新视图
class XKRefreshView: UIView {
    
    /// 旋转标记
    private var rotateFlag = false {
        didSet {
            rotateTipicon()
        }
    }
    
    @IBOutlet weak var loadingIconView: UIImageView!
    
    @IBOutlet weak var tipView: UIView!
    
    @IBOutlet weak var tipIconView: UIImageView!
    
    
    /// 加载xib 
    class func refreshView () ->XKRefreshView {
        let nib = UINib(nibName: "XKRefreshView", bundle: nil)
        return nib.instantiateWithOwner(nil, options: nil).last as! XKRefreshView
    }
    
    /// 旋转图标动画
    private func rotateTipicon () {
        var angle = CGFloat(M_PI)
        angle += rotateFlag ? -0.0000001 : 0.0000001
        
        // 旋转动画，特点：顺时针优先 + `就近原则`
        UIView.animateWithDuration(0.5) { () -> Void in
            
            self.tipIconView.transform = CGAffineTransformRotate(self.tipIconView.transform, CGFloat(angle))
        }
    }
    /// 播放加载动画
    private func startAnimation() {
        
        tipView.hidden = true
        
        // 判断动画是否已经被添加
        let key = "transform.rotation"
        if loadingIconView.layer.animationForKey(key) != nil {
            return
        }
        
        print("加载动画播放")
        
        let anim = CABasicAnimation(keyPath: key)
        
        anim.toValue = 2 * M_PI
        anim.repeatCount = MAXFLOAT
        anim.duration = 0.5
        anim.removedOnCompletion = true
        
        loadingIconView.layer.addAnimation(anim, forKey: key)

    }
    
    /// 停止加载动画
    private func stopAnimation() {
        tipView.hidden = false
        
        loadingIconView.layer.removeAllAnimations()
    }

    
    
}
